package com.qmx.launcher.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.RectF;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.open.androidtvwidget.bridge.RecyclerViewBridge;
import com.open.androidtvwidget.leanback.adapter.GeneralAdapter;
import com.open.androidtvwidget.leanback.recycle.LinearLayoutManagerTV;
import com.open.androidtvwidget.leanback.recycle.RecyclerViewTV;
import com.open.androidtvwidget.view.MainUpView;
import com.qmx.launcher.QMXApplication;
import com.qmx.launcher.R;
import com.qmx.launcher.activity.base.BaseActivity;
import com.qmx.launcher.adapter.ContactRecyclerViewPresenter;
import com.qmx.launcher.bean.ContactList;
import com.qmx.launcher.bean.ContactModel;
import com.qmx.launcher.bean.LzyResponse;
import com.qmx.launcher.callback.JsonCallback;
import com.qmx.launcher.constant.AppConstant;
import com.qmx.launcher.constant.ComParamContact;
import com.qmx.launcher.token.TokenManager;
import com.qmx.launcher.utils.RealmUtils;
import com.siberiadante.customdialoglib.EditDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import app.dinus.com.itemdecoration.LinearDividerItemDecoration;
import io.realm.Realm;
import io.realm.RealmList;

//import android.support.v7.widget.DividerItemDecoration;

public class ContactGroupActivity extends BaseActivity implements RecyclerViewTV.OnItemListener {


    private Context mContext;
    private RecyclerViewTV mRecyclerView;
    private EditText contact_group_tips;
    private MainUpView mainUpView1;
    private RecyclerViewBridge mRecyclerViewBridge;
    private View oldView;
    private ContactRecyclerViewPresenter mRecyclerViewPresenter;
    private GeneralAdapter mGeneralAdapter;
    private int roomId;
    private int password;
    private Gson mGson = new Gson();

    private Realm defaultRealm;
    private RealmList<ContactModel> itemList;
    private RealmUtils realmUtils;
    private int Pos = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_group);

        mContext = this;
        defaultRealm = QMXApplication.getRealmInstance();
        realmUtils = new RealmUtils(defaultRealm);

        mRecyclerView = (RecyclerViewTV) findViewById(R.id.rv_contact_list);
        contact_group_tips = findViewById(R.id.contact_group_tips);
        mainUpView1 = (MainUpView) findViewById(R.id.mainUpView1);
        mainUpView1.setEffectBridge(new RecyclerViewBridge());
        // 注意这里，需要使用 RecyclerViewBridge 的移动边框 Bridge.
        mRecyclerViewBridge = (RecyclerViewBridge) mainUpView1.getEffectBridge();
        mRecyclerViewBridge.setUpRectResource(R.drawable.blue_frame);
        float density = getResources().getDisplayMetrics().density;
        RectF receF = new RectF(getDimension(R.dimen.w_5) * density, getDimension(R.dimen.h_5) * density,
                getDimension(R.dimen.w_5) * density, getDimension(R.dimen.h_5) * density);
        mRecyclerViewBridge.setDrawUpRectPadding(receF);

        ContactList();

        saveOrUpdate();
        recyclerViewLinerLayout(RecyclerView.VERTICAL);

        mRecyclerView.setOnItemListener(this);
        // item 单击事件处理.
        mRecyclerView.setOnItemClickListener(new RecyclerViewTV.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerViewTV parent, View itemView, int position) {
                Toast.makeText(mContext, "点击位置" + position, Toast.LENGTH_SHORT).show();
                startActivity(new Intent(mContext, GroupMembersActivity.class));
                //                showInputDialog();
            }
        });

    }


    public void saveOrUpdate() {
        //        RealmResults<ContactModel> list = defaultRealm.where(ContactModel.class)
        //                .findAll();
        final List<ContactModel> list = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            ContactModel contactModel = new ContactModel();
            contactModel.setName("修改 " + i);
            contactModel.setMobile(123456789 + i);
            contactModel.setMdate(new Date());
            contactModel.setId(i);
            list.add(contactModel);
        }
        realmUtils.insertOrUpdateBatch(list);

        defaultRealm.executeTransactionAsync(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                //                realmUtils.insertOrUpdateBatch(list);
                //                    realm.copyToRealmOrUpdate(contactModel);
                //                                                         parentContact.getItemList().add(contactModel);
                //                realm.copyToRealmOrUpdate(list);
            }
        });
    }

    private void recyclerViewLinerLayout(int orientation) {
        LinearLayoutManagerTV layoutManager = new LinearLayoutManagerTV(this);
        layoutManager.setOrientation(orientation);
        mRecyclerView.setLayoutManager(layoutManager);
        //        mRecyclerView.setFocusable(false);
        mRecyclerViewPresenter = new ContactRecyclerViewPresenter(defaultRealm.where(ContactModel
                .class).findAll());
        mGeneralAdapter = new GeneralAdapter(mRecyclerViewPresenter);
        mRecyclerView.setAdapter(mGeneralAdapter);
        mRecyclerView.setHasFixedSize(true);
        LinearDividerItemDecoration dividerItemDecoration = new LinearDividerItemDecoration(
                this, LinearDividerItemDecoration.LINEAR_DIVIDER_VERTICAL);
        mRecyclerView.addItemDecoration(dividerItemDecoration);
        //        mRecyclerView.setSelectedItemOffset(10, 10); // 测试移动间距.
        mRecyclerView.setFocusable(true);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(500);
                    mRecyclerView.setDefaultSelect(0);
                    //
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * @author ChengXiangtong
     * @create 2018/12/29
     * @Describe 加载联系人数据
     */
    public void ContactList() {
        OkGo.<LzyResponse<ContactList>>post(AppConstant.Url + ComParamContact.contactList.PATH)
                .headers(ComParamContact.contactList.TOKEN, TokenManager.getInstance().getAuthModel().getToken())
                .execute(new JsonCallback<LzyResponse<ContactList>>() {
                    @Override
                    public void onSuccess(Response<LzyResponse<ContactList>> response) {
                        String str = mGson.toJson(response.body().data);

                        List<?> content = mGson.fromJson(str,ContactList.class).getContent();
                        Log.i("ContactList", content.size() + "");

                        //                        try {
                        //                            JSONObject jsonObject = new JSONObject(response.body());
                        //                            Log.i("ContactList", jsonObject.toString());
                        //                            String json = jsonObject.optString("code");
                        //                            String msg = jsonObject.optString("msg");
                        //                        } catch (JSONException e) {
                        //                            e.printStackTrace();
                        //                        }

                        Log.i("ContactList", response.body() + "");


                    }

                    @Override
                    public void onError(Response<LzyResponse<ContactList>> response) {
                        Log.i("ContactListonError", response.getException().getMessage());
                        showToast(response.getException().getMessage());
                    }
                });
    }


    public void joinMeeting() {
        OkGo.<String>post(AppConstant.Url + ComParamContact.Launch.PATH)
                .params(ComParamContact.Launch.TOKEN, TokenManager.getInstance().getAuthModel().getToken())
                .params(ComParamContact.Launch.__TOKEN__, __TOKEN__)
                .params(ComParamContact.Launch.ROOM_ID, roomId)
                .params(ComParamContact.Launch.CLIENT_ID, sharedPreferences.getString(AppConstant.CLIENT_ID, ""))
                .params(ComParamContact.Launch.PASSWORD, password)
                .execute(new JsonCallback<String>() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        //                        String str = mGson.toJson(response.body());
                        try {
                            JSONObject jsonObject = new JSONObject(response.body());
                            String json = jsonObject.optString("code");
                            String msg = jsonObject.optString("msg");
                            //                        100：平台无此会议号 101：请输入密码 102：密码错误 103：方数不足 104：加入成功 104：短线重连
                            if (json.equals("1")) {
                                Intent intent = new Intent(mContext, RoomActivity.class);
                                //                                Log.e("roomId==", roomId);
                                intent.putExtra("roomId", roomId);
                                startActivity(intent);
                            } else if (json.equals("0")) {
                                showToast(msg);
                            } else if (json.equals("102")) {
                                showInputDialog();
                                showToast(msg);
                            } else if (json.equals("102")) {
                                showToast(msg);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        Log.i("joinMeeting", response.body() + "");


                    }

                    @Override
                    public void onError(Response<String> response) {
                        Log.i("onError", response.getException().getMessage());
                        showToast(response.getException().getMessage());
                    }
                });
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (Pos == 0 && keyCode == KeyEvent.KEYCODE_DPAD_UP) {
            contact_group_tips.setFocusable(true);
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        defaultRealm.close();
    }

    @Override
    public void onItemPreSelected(RecyclerViewTV parent, View itemView, int position) {
        mRecyclerViewBridge.setUnFocusView(itemView);
    }

    @Override
    public void onItemSelected(RecyclerViewTV parent, View itemView, int position) {
        mRecyclerViewBridge.setFocusView(itemView, 1.0f);
        oldView = itemView;
        Pos = position;
    }


    @Override
    public void onReviseFocusFollow(RecyclerViewTV parent, View itemView, int position) {
        mRecyclerViewBridge.setFocusView(itemView, 1.0f);
        oldView = itemView;
    }

    private AlertDialog inputDlg;

    @SuppressLint("ResourceAsColor")
    private void showInputDialog() {
        final EditDialog dialog = new EditDialog(this).builder();
        dialog.setTitle("请输入会议密码");
        dialog.setCancelable(false);
        dialog.setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.setPositiveButton("确定", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final String msg = dialog.getMsg();
                Toast.makeText(mContext, "输入内容为：" + msg, Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }
        });
        dialog.show();
    }

}
